﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ElectronicShoppingMall.Service.Data;
using ElectronicShoppingMall.Service.Models.Enterprise;
using ElectronicShoppingMall.Service.Models.Shared;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using ElectronicShoppingMall.Service.Services.Interface.Enterprise;

namespace ElectronicShoppingMall.Service.Services.Enterprise
{
    public class EmployeeUserService :  IDisposable
    {
        private readonly ElectronicShoppingMallContext data;

        public EmployeeUserService()
        {
            data = new ElectronicShoppingMallContext();
        }

        public void CreateEmployee(Employee employee)
        {
            throw new NotImplementedException();
        }

        public void CreateRole(string roleName, int[] permissionIds)
        {
            throw new NotImplementedException();
        }

        //激活员工账号
        public void ActivateEmployee(int employeeId, string activateCode)
        {
            var employee = data.Employees.SingleOrDefault(e => e.EmployeeId == employeeId);
            if (employee != null && (employee.ActivateCode != activateCode || employee.IsActivate == true))
            {
                throw new Exception("激活码错误或无法激活");
            }
        }

        public void DeleteEmployeeByEmployeeId(int employeeId)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId"></param>
        public void DeleteRoleByRoleId(int roleId)
        {
            var role = data.Roles.SingleOrDefault(r => r.RoleId == roleId);
            if (role.IsStatic)
                throw new Exception("系统角色不可删除");
            else
            {
                role.Permissions.Clear();
                var employees = role.Employees;
                foreach (var employee in employees)
                {
                    if (employee.Roles.Count <= 1)
                    {
                        employee.Roles.Add(data.Roles.SingleOrDefault(r => r.RoleId == 2));
                    }
                }
                role.Employees.Clear();
                data.SaveChanges();
                data.Roles.Remove(role);
                data.SaveChanges();
            }
        }

        public void Dispose()
        {
            data.Dispose();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="ip"></param>
        /// <returns></returns>
        public EmployeeUserModel Login(string account, string password, string ip)
        {
            EmployeeUserModel result;
            var user = data.Users.SingleOrDefault(u => u.Account == account && u.Password == password);
            if (user == null)
            {
                throw new Exception("用户名或密码错误");
            }
            var employee = data.Employees.SingleOrDefault(e => e.UserId == user.UserId);
            var record = new EmployeeLoginRecord()
            {
                EmployeeId = employee.EmployeeId,
                LoginTime = DateTime.Now,
                LoginIP = "113.251.45.172"
            };
            record.LoginAddress = GetstringIpAddress(record.LoginIP);
            data.EmployeeLoginRecords.Add(record);
            data.SaveChanges();
            result = new EmployeeUserModel()
            {
                Account = user.Account,
                Password = user.Password,
                Name = user.NickName,
                UserId = user.UserId,
                EmployeeId = employee.EmployeeId,
                UserAvatar = user.UserAvatar
            };
            return result;
        }
        //获取IP地址
        private static string GetstringIpAddress(string strIP) //strIP为IP  
        {
            var url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP;
            //实例化
            var client = new WebClient();
            //上传并接收数据
            var responseData = client.DownloadData(url);
            //接收返回的json的流数据，并转码
            var srcString = Encoding.UTF8.GetString(responseData);
            var jsonReader = new JavaScriptSerializer();
            var address = jsonReader.Deserialize<LoginAddressModel>(srcString);
            return address.Data.Country + address.Data.Isp + address.Data.City + address.Data.Area + "地区";
        }
        /// <summary>
        /// 获取员工信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public UserModel GetEmployeeUserInformation(int userId, int employeeId)
        {
            var result = new UserModel();
            var user = data.Users.SingleOrDefault(u => u.UserId == userId);
            var employee = data.Employees.SingleOrDefault(e => e.EmployeeId == employeeId);
            result.UserId = user.UserId;
            result.NickName = user.NickName;
            result.PhoneNumber = user.PhoneNumber;
            result.UserAvatar = user.UserAvatar;
            result.Gender = user.Gender;
            result.Email = user.Email;
            result.Birthday = user.Birthday;
            result.Account = user.Account;
            result.Password = user.Password;
            result.CreateTime = user.CreateTime.ToString(CultureInfo.InvariantCulture);
            result.Position = employee.Position;
            return result;
        }
        /// <summary>
        /// 修改用户头像
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="employeeId"></param>
        /// <param name="imgBase"></param>
        /// <returns></returns>
        public UserModel ChangeUserAvatar(int userId, int employeeId, string imgBase)
        {
            var user = data.Users.SingleOrDefault(u => u.UserId == userId);
            try
            {
                var img = imgBase.Split(',');
                var bt = Convert.FromBase64String(img[1]);
                var myGuid = Guid.NewGuid().ToString();
                var path = "D:\\stage-file\\userAvatar\\" +
                              myGuid + ".png";
                var dataPath = "http://localhost/userAvatar/" + myGuid + ".png";
                File.WriteAllBytes(path, bt);
                user.UserAvatar = dataPath;
                data.SaveChanges();
                var newUser = data.Users.SingleOrDefault(u => u.UserId == userId);
                var employee = data.Employees.SingleOrDefault(u => u.EmployeeId == employeeId);
                var result = new UserModel
                {
                    UserId = newUser.UserId,
                    NickName = newUser.NickName,
                    PhoneNumber = newUser.PhoneNumber,
                    UserAvatar = newUser.UserAvatar,
                    Gender = newUser.Gender,
                    Email = newUser.Email,
                    Birthday = newUser.Birthday,
                    Account = newUser.Account,
                    Password = newUser.Password,
                    Position = employee.Position,
                    CreateTime = newUser.CreateTime.ToString()
                };
                return result;
            }
            catch
            {
                return null;
            }
        }
       /// <summary>
       /// 修改用户信息
       /// </summary>
       /// <param name="userId"></param>
       /// <param name="employeeId"></param>
       /// <param name="userDetails"></param>
       /// <returns></returns>
        public UserModel ChangeUserDetails(int userId, int employeeId, UserDetailsModel userDetails)
        {
            var user = data.Users.SingleOrDefault(u => u.UserId == userId);
            try
            {
                user.NickName = userDetails.NickName;
                user.Birthday = DateTime.ParseExact(userDetails.Birthday + " 13:00:21 872", "yyyy-MM-dd HH:mm:ss fff",
                    null);
                user.Email = userDetails.Email;
                user.Gender = userDetails.Gender == "男" ? true : false;
                user.PhoneNumber = userDetails.PhoneNumber;
                data.SaveChanges();
                var result = GetEmployeeUserInformation(userId, employeeId);
                return result;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 获取角色
        /// </summary>
        /// <returns></returns>
        public List<RoleModel> GetRoles()
        {
            var result = new List<RoleModel>();
            var roles = data.Roles;
            foreach (var role in roles)
            {
                var temp = new RoleModel()
                {
                    RoleId = role.RoleId,
                    Name = role.Name,
                    IsStatic = role.IsStatic,
                    CreationTime = role.CreationTime
                };
                result.Add(temp);
            }
            return result;
        }
        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<Permission> GetPermissonByRoleId(int id)
        {
            var role = data.Roles.SingleOrDefault(r => r.RoleId == id);
            return role.Permissions.ToList();
        }
        /// <summary>
        /// 修改角色权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="roleName"></param>
        /// <param name="permissionIds"></param>
        public void ChangeRolePermission(int roleId, string roleName, List<int> permissionIds)
        {
            var permissions = data.Permissions.ToList();
            var flag = true;
            foreach (var perId in permissionIds)
            {
                flag = permissions.Find(p => p.PermissionId == perId) != null ? true : false;
            }
            if (flag)
            {
                var role = data.Roles.SingleOrDefault(r => r.RoleId == roleId);
                role.Name = roleName;
                role.Permissions.Clear();
                foreach (var perId in permissionIds)
                {
                    role.Permissions.Add(permissions.Find(p => p.PermissionId == perId));
                }
                data.SaveChanges();
            }
            else
            {
                throw new Exception("权限ID有误");
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="permissionIds"></param>
        public void AddRole(string roleName, List<int> permissionIds)
        {
            var permissions = data.Permissions.ToList();
            var flag = true;
            foreach (var perId in permissionIds)
            {
                flag = permissions.Find(p => p.PermissionId == perId) != null ? true : false;
            }
            if (flag)
            {
                var role = new Role()
                {
                    Name = roleName,
                    CreationTime = DateTime.Now,
                    IsStatic = false
                };
                foreach (var perId in permissionIds)
                {
                    role.Permissions.Add(permissions.Find(p => p.PermissionId == perId));
                }
                data.Roles.Add(role);
                data.SaveChanges();
            }
            else
            {
                throw new Exception("权限ID有误");
            }
        }
       /// <summary>
       /// 获取所有员工信息
       /// </summary>
       /// <returns></returns>
        public List<EmployeeUserDetailsModel> GetAllEmployeeUser()
        {
            var result = new List<EmployeeUserDetailsModel>();
            var employees = data.Employees.ToList();
            foreach (var employee in employees)
            {
                var user = employee.User;
                var roles = employee.Roles;
                var temp = new EmployeeUserDetailsModel
                {
                    UserId = user.UserId,
                    EmployeeId = employee.EmployeeId,
                    Account = user.Account,
                    CreateTime = user.CreateTime.ToString(),
                    Email = user.Email,
                    Password = user.Password,
                    NickName = user.NickName,
                    IsActivate = employee.IsActivate == true ? "是" : "否",
                    PhoneNumber = user.PhoneNumber,
                };
                if (user.Gender != null)
                {
                    temp.Gender = user.Gender == true ? "男" : "女";
                }
                else
                {
                    temp.Gender = "尚未填写";
                }
                if (user.Birthday != null)
                {
                    temp.Birthday = user.Birthday.ToString();
                }
                else
                {
                    temp.Birthday = "尚未填写";
                }
                if (employee.EmployeeLoginRecords.Count == 0)
                {
                    temp.LastLoginTime = "从未登录";
                    temp.LastLoginIpAndAddress = "从未登录";
                }
                else
                {
                    temp.LastLoginTime = employee.EmployeeLoginRecords.Last().LoginTime.ToString();
                    temp.LastLoginIpAndAddress = employee.EmployeeLoginRecords.Last().LoginIP + "," +
                                                 employee.EmployeeLoginRecords.Last().LoginAddress;
                }
                var roleNames = new StringBuilder();
                foreach (var role in employee.Roles)
                {
                    roleNames.Append(role.Name + " ");
                }
                temp.RoleName = roleNames.ToString();
                result.Add(temp);
            }
            return result;
        }
        /// <summary>
        /// 获取员工权限
        /// </summary>
        /// <param name="employeeId"></param>
        /// <returns></returns>
        public List<Permission> GetUserPermissions(int employeeId)
        {
            var employee = data.Employees.SingleOrDefault(e => e.EmployeeId == employeeId);
            return employee.Permissions.ToList();
        }
        /// <summary>
        /// 修改员工权限
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="permissionIds"></param>
        public void ChangeEmployeePermissions(int employeeId, List<int> permissionIds)
        {
            var employee = data.Employees.SingleOrDefault(e => e.EmployeeId == employeeId);
            employee.Permissions.Clear();
            var permissions = data.Permissions;
            foreach (var perId in permissionIds)
            {
                var permission = permissions.SingleOrDefault(per => per.PermissionId == perId);
                employee.Permissions.Add(permission);
            }
            data.SaveChanges();
        }

        public List<AdminLogModel> GetOperationLogs()
        {
            List<AdminLogModel> result = new List<AdminLogModel>();
            var logs = data.AdminLogs.ToList();
            foreach(var log in logs)
            {
                AdminLogModel temp = new AdminLogModel
                {
                    RecordId = log.RecordId,
                    EmployeeId = log.EmployeeId,
                    OperatDetail = log.OperatDetail,
                    Operater = log.Operater,
                    OperationTime = log.OperationTime.ToString(),
                    Result = log.Result
                };
                result.Add(temp);
            }
            return result;
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="userId"></param>
        public void DeleteEmployeeUser(int userId)
        {
            var user = data.Users.SingleOrDefault(u => u.UserId == userId);
            var employee = user.Employees.First();
            employee.Permissions.Clear();
            employee.Roles.Clear();
            data.Employees.Remove(employee);
            user.Employees.Clear();
            data.Users.Remove(user);
            data.SaveChanges();
        }
        /// <summary>
        /// 添加员工
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="userRoles"></param>
        public void AdminAddEmployee(EmployeeUserDetailsModel userInfo, List<int> userRoles)
        {
            var user = new User()
            {
                NickName = userInfo.NickName,
                Account = userInfo.Account,
                UserAvatar = "../Content/src/img/userAvatar/user.png",
                CreateTime = DateTime.Now,
                Email = userInfo.Email,
                PhoneNumber = userInfo.PhoneNumber,
            };
            if (userInfo.Password == null)
            {
                var ran = new Random();
                user.Password = "Stage" + ran.Next(1, 99);
            }
            else
            {
                if (userInfo.Password == "random")
                {
                    var ran = new Random();
                    user.Password = "Stage" + ran.Next(1, 99);
                }
                else
                {
                    user.Password = userInfo.Password;
                }
            }

            data.Users.Add(user);
            data.SaveChanges();
            if (userRoles == null)
            {
                var employee = new Employee();
                employee.Roles.Add(data.Roles.SingleOrDefault(r => r.RoleId == 2));
                employee.UserId = user.UserId;
                employee.Position = "库管员";
                employee.IsActivate = false;
                employee.ActivateCode = Guid.NewGuid().ToString();
                data.Employees.Add(employee);
                data.SaveChanges();
                if (userInfo.IsSendMail == "send")
                {
                    SendEmial.SendEmail(user.Email, "Stage管理通知",
                        "您的密码被修改为" + user.Password + "激活链接为:http://localhost:27651/Home/ActivateEmployee?employeeid=" +
                        employee.EmployeeId + "&amp;" + "activateCode=" + employee.ActivateCode);
                }
            }
            else
            {
                var employee = new Employee();
                var position = new StringBuilder();
                foreach (var roleId in userRoles)
                {
                    var role = data.Roles.Single(r => r.RoleId == roleId);
                    employee.Roles.Add(role);
                    position.Append(role.Name + ",");
                }
                employee.UserId = user.UserId;
                employee.Position = position.ToString();
                employee.IsActivate = false;
                employee.ActivateCode = Guid.NewGuid().ToString();
                data.Employees.Add(employee);
                data.SaveChanges();
                if (userInfo.IsSendMail == "send")
                {
                    SendEmial.SendEmail(user.Email, "Stage管理通知",
                        "您的密码被修改为" + user.Password + "激活链接为:http://localhost:27651/Home/ActivateEmployee?employeeid=" +
                        employee.EmployeeId + "&amp;" + "activateCode=" + employee.ActivateCode);
                }
            }
        }
        /// <summary>
        /// 管理员修改员工信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="userRoles"></param>
        public void AdminChangeUserDetails(EmployeeUserDetailsModel userInfo, List<int> userRoles)
        {
            var user = data.Users.SingleOrDefault(u => u.UserId == userInfo.UserId);
            user.NickName = userInfo.NickName;
            user.Email = userInfo.Email;
            user.PhoneNumber = userInfo.PhoneNumber;
            if (userInfo.Password != null)
            {
                if (userInfo.Password == "random")
                {
                    var ran = new Random();
                    user.Password = "Stage" + ran.Next(1, 99);
                }
                else
                {
                    user.Password = userInfo.Password;
                }
                SendEmial.SendEmail(user.Email, "Stage管理通知", "您的密码被修改为" + user.Password);
            }
            if (userRoles != null)
            {
                var employees = user.Employees.ToList();
                foreach (var employee in employees)
                {
                    employee.Roles.Clear();
                    foreach (var roleId in userRoles)
                    {
                        employee.Roles.Add(data.Roles.Single(r => r.RoleId == roleId));
                    }
                }
            }

            data.SaveChanges();
        }
    }
}